﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

namespace DnsmasqUtility
{
    internal class Program
    {
        private const string Pattern = @"^\s*(?<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+(?<domain>\S*)\s*$";

        private static void Main(string[] args)
        {
            if (args.Any())
            {
                foreach (string s in args.Where(File.Exists))
                {
                    ParserHost(s);
                }
            }
            else
            {
                Console.WriteLine("Drag host file to this app");
            }
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }

        private static void ParserHost(string s)
        {
            var list = new List<string>();
            Console.WriteLine(s);
            Console.WriteLine("Parser...");
            using (var sr = new StreamReader(s))
            {
                while (sr.Peek() > 0)
                {
                    string l = sr.ReadLine();
                    if (string.IsNullOrWhiteSpace(l)) continue;
                    if (Regex.IsMatch(l, Pattern))
                    {
                        Match match = Regex.Match(l, Pattern);
                        list.Add(string.Format("address=/{0}/{1}", match.Groups["domain"], match.Groups["ip"]));
                    }
                }
            }
            Console.WriteLine("{0} host(s) parsered", list.Count);
            // ReSharper disable once AssignNullToNotNullAttribute
            using (var sw = new StreamWriter(Path.Combine(Path.GetDirectoryName(s), "dnsmasq.txt")))
            {
                foreach (string l in list)
                {
                    sw.WriteLine(l);
                }
            }
            Console.WriteLine("Dnsmasq file generated!");
        }
    }
}